<?php
namespace models;

class Current_user {

	private static $user;

	public static function get_user(){
		if(!isset(self::$user)){
			$CI =& get_instance();
			$CI->load->library('session');

            $username = $CI->session->userdata('username');
			if(!$username) return false;

			$u = $CI->doctrine->em->getRepository('models\Akun')->findBy(array('username' => $username));
			if(!$u) $u = $CI->doctrine->em->getRepository('models\Akun')->findBy(array('email' => $username));
			if(!$u) return false;

			self::$user = $u[0];
		}
		return self::$user;
	}

	public static function login($username, $password){
		$CI =& get_instance();
		$CI->load->library('session');

		$u = $CI->doctrine->em->getRepository('models\Akun')->findBy(array(
			'username' => $username,
			'password' => Akun::encode_password($password),
		));
		if(!$u){
			$u = $CI->doctrine->em->getRepository('models\Akun')->findBy(array(
				'email' => $username,
				'password' => Akun::encode_password($password),
			));
		}
		if($u){
            $CI->session->set_userdata(array(
                'username' => $username,
			));
			self::$user = $u[0];
			self::$user->set_last_login(new \DateTime('now'));
			$CI->doctrine->em->flush();
			return true;
		} 
		return false;
	}

	public static function get_kategori(){
		$kategori = substr(get_class(self::$user),7);
		if($kategori == 'Akun') $kategori = 'Administrator';
		return $kategori;
	}

	public static function logout(){
		$CI =& get_instance();
		$CI->load->library('session');
		$CI->session->sess_destroy();
	}

	public static function previlege($list_kategori){
		$kategori_array = explode('|',$list_kategori);
		foreach ($kategori_array as $kategori) {
			if ($kategori == self::get_kategori()) {
				return true;
			}
		}
		return false;
	}

	public function __clone() {
	    trigger_error('Clone is not allowed.', E_USER_ERROR);
	}
	
}
